#include "StdAfx.h"
#include "LayoutController.h"
#include "Layout.h"

#include <QMessageBox>
#include <QString>
#include <QPixmap>
#include <QVariant>

LayoutController::LayoutController(void) : activeLayout_(nullptr)
{
	layoutView_ = new LayoutView(ui_.ui.centralWidget);
	ui_.ui.horizontalLayout->removeWidget(ui_.ui.graphicsView);
    ui_.ui.horizontalLayout->addWidget(layoutView_);

	//MAJOR HACK
    layoutView_->setObjectName(QString::fromUtf8("graphicsView"));
    layoutView_->setRenderHints(QPainter::Antialiasing|QPainter::HighQualityAntialiasing|QPainter::SmoothPixmapTransform|QPainter::TextAntialiasing);
    layoutView_->setDragMode(QGraphicsView::ScrollHandDrag);




	//layoutView_.AttachToGraphicsView( ui_.ui.graphicsView);
	ui_.setWindowState(ui_.windowState() ^ Qt::WindowMaximized); //sets window to maximized initially
	
	connect(ui_.ui.actionExit, SIGNAL(triggered()), SLOT(exitClicked()));
	
	connect(ui_.ui.actionZoomIn, SIGNAL(clicked()), SLOT(zoomInClicked()));
	connect(ui_.ui.actionZoomOut, SIGNAL(clicked()), SLOT(zoomOutClicked()));
	
	connect(ui_.ui.actionSave, SIGNAL(triggered()), SLOT(saveClicked()));
	connect(ui_.ui.actionOpen, SIGNAL(triggered()), SLOT(loadClicked()));
	connect(ui_.ui.actionNew, SIGNAL(triggered()), SLOT(newClicked()));

	connect(ui_.ui.actionDelete, SIGNAL(triggered()), SLOT(deleteClicked()));

	connect(PrefabRepository::Instance(), SIGNAL(PrefabAdded(ObjectPrefab*)), SLOT(prefabAdded(ObjectPrefab*)));

	connect(ui_.ui.Left_List, 
		SIGNAL(itemClicked(QListWidgetItem*)), SLOT(placeItem(QListWidgetItem*)));

	connect(layoutView_, SIGNAL(SelectionChanged()), SLOT(ViewSelectionChanged()));
	addFurniture();

	SwitchToLayout(new Layout());

	scaleCur_ = 1;
}

void LayoutController::deleteClicked()
{
	auto selectedItems = layoutView_->getSelectedItem();
	for (int i = 0;i<selectedItems.size();i++)
	{
		auto objectVisual = static_cast<ObjectVisual*>(selectedItems[i]);
		activeLayout_->RemoveObject(objectVisual->LayoutObj());
	}
}

void LayoutController::prefabAdded(ObjectPrefab* prefab)
{
	QListWidgetItem *newItem = new QListWidgetItem;
	newItem->setText(prefab->Name());
	ui_.ui.Left_List->addItem(newItem);
	//TODO: Possible memory issue
	//role = 1k = show text
	//role = 0 = no text
	newItem->setData(1000, QVariant::fromValue((void*)prefab));

}
LayoutController::~LayoutController(void)
{
	delete layoutView_;
}

void LayoutController::exitClicked()
{
	QMessageBox msgBox;
	msgBox.setText("Are you sure you want to exit?\nAny unsaved changes may be discarded");
	msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::Cancel);
	msgBox.setDefaultButton(QMessageBox::Cancel);
	int ret = msgBox.exec();
	switch (ret) 
	{
		case QMessageBox::Yes:
			// Yes was clicked
			exit(0);
		case QMessageBox::Cancel:
			// Cancel was clicked
			break;
		default:
			// should never be reached
			break;		
	}
}

void LayoutController::placeItem(QListWidgetItem* item)
{
	ObjectPrefab* prefab = static_cast<ObjectPrefab*>(item->data(1000).value<void*>());


	LayoutObject* lo = new LayoutObject();
	lo->SetPrefabGuid(prefab->Guid());

	activeLayout_->AddObject(lo);

}

void LayoutController::SaveLayout()
{
	if(activeLayout_ != nullptr && activeLayout_->IsDirty())
	{
		saveToFile();
	}
}

void LayoutController::addFurniture()
{
	QString dirPrefix = "Images\\";

	ObjectPrefab* doubleBed = new ObjectPrefab();
	doubleBed->SetGuid("DOUBLEBED");
	doubleBed->SetName("Double Bed");
	doubleBed->SetPixmap(QPixmap(dirPrefix + "DoubleBed2.png"));
	PrefabRepository::Instance()->AddPrefab(doubleBed);
	
	ObjectPrefab* armChair = new ObjectPrefab();
	armChair->SetGuid("ARMCHAIR");
	armChair->SetName("ArmChair V1");
	armChair->SetPixmap(QPixmap(dirPrefix + "ArmChair.png"));
	PrefabRepository::Instance()->AddPrefab(armChair);

	/*
	QList<QString> furnitureList;
	furnitureList <<"ArmChair" << "DiningTable" << "Doorway" << "DoubleBed" << "DoubleDoorway" << "RoundTable";

	for (int i = 0; i < furnitureList.size(); i++)
	{
		QListWidgetItem *newItem = new QListWidgetItem;
		newItem->setText(furnitureList[i]);
		ui_.ui.Left_List->insertItem(i, newItem);
	}
	*/
}

void LayoutController::saveClicked()
{
	saveToFile();
}

void LayoutController::loadClicked()
{
	loadFromFile();
}
void LayoutController::newClicked()
{
	Layout* layout = new Layout();
	SwitchToLayout(layout);
}
void LayoutController::saveToFile()
{
	//Display the file dialog and get any existing files with our custom floorplan extension
	QString fileName = QFileDialog::getSaveFileName(&ui_, tr("Save Floor Plan"), "", tr("Floor Plan (*.fpl);;All Files (*)"));

	if (fileName.isEmpty())						//If there are no existing files
	{
         return;
	}
    else										//If there are existing files
	{
        QFile file(fileName);

        if (!file.open(QIODevice::WriteOnly))	//If we cannot open the file, display error message and stop
		{
            QMessageBox::information(&ui_, tr("Unable to open file"), file.errorString());
            return;
        }

		//QDataStream out(&file);					//If we can save, then do so
        //out.setVersion(QDataStream::Qt_4_5);
        //out << testing;
		activeLayout_->Save(fileName);
    }
}

void LayoutController::loadFromFile()
{
	//Display the file dialog and get any existing files with our custom floorplan extension
	QString fileName = QFileDialog::getOpenFileName(&ui_, tr("Open Floor Plan"), "", tr("Floor Plan (*.fpl);;All Files (*)"));

	 if (fileName.isEmpty())					//If there are no existing files
	 {
         return;
	 }
     else										//If there are existing files
	 {
         QFile file(fileName);

         if (!file.open(QIODevice::ReadOnly))	//If we cannot open the file, display error message
		 {
             QMessageBox::information(&ui_, tr("Unable to open file"), file.errorString());
             return;
         }
         //QDataStream in(&file);
         //in.setVersion(QDataStream::Qt_4_5);
         //in >> temp;
		 Layout* layout = Layout::Load(fileName);
		 
		 SwitchToLayout(layout);
     }
}